import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { RuleConfig, RuleBasicInfo, RuleListParams, RulePreview } from '../../types/rule';
import { ruleApi } from '../../services/api';

interface RuleState {
  loading: boolean;
  ruleList: RuleBasicInfo[];
  currentRule: RuleConfig | null;
  rulePreview: RulePreview | null;
  total: number;
  page: number;
  size: number;
  error: string | null;
}

const initialState: RuleState = {
  loading: false,
  ruleList: [],
  currentRule: null,
  rulePreview: null,
  total: 0,
  page: 1,
  size: 10,
  error: null,
};

// 异步操作
export const fetchRuleList = createAsyncThunk(
  'rule/fetchRuleList',
  async (params: RuleListParams) => {
    const response = await ruleApi.getRuleList(params);
    return response.data;
  }
);

export const fetchRuleDetail = createAsyncThunk(
  'rule/fetchRuleDetail',
  async (id: string) => {
    const response = await ruleApi.getRuleDetail(id);
    return response.data;
  }
);

export const createRule = createAsyncThunk(
  'rule/createRule',
  async (rule: RuleConfig) => {
    const response = await ruleApi.createRule(rule);
    return response.data;
  }
);

export const updateRule = createAsyncThunk(
  'rule/updateRule',
  async ({ id, rule }: { id: string; rule: RuleConfig }) => {
    const response = await ruleApi.updateRule(id, rule);
    return response.data;
  }
);

export const deleteRule = createAsyncThunk(
  'rule/deleteRule',
  async (id: string) => {
    await ruleApi.deleteRule(id);
    return id;
  }
);

export const previewRule = createAsyncThunk(
  'rule/previewRule',
  async (rule: RuleConfig) => {
    const response = await ruleApi.previewRule(rule);
    return response.data;
  }
);

export const toggleRuleStatus = createAsyncThunk(
  'rule/toggleRuleStatus',
  async ({ id, status }: { id: string; status: 'active' | 'disabled' }) => {
    const response = await ruleApi.updateRuleStatus(id, status);
    return response.data;
  }
);

const ruleSlice = createSlice({
  name: 'rule',
  initialState,
  reducers: {
    setCurrentRule: (state, action: PayloadAction<RuleConfig | null>) => {
      state.currentRule = action.payload;
    },
    updateCurrentRule: (state, action: PayloadAction<Partial<RuleConfig>>) => {
      if (state.currentRule) {
        state.currentRule = { ...state.currentRule, ...action.payload };
      }
    },
    clearError: (state) => {
      state.error = null;
    },
    setPage: (state, action: PayloadAction<number>) => {
      state.page = action.payload;
    },
    setSize: (state, action: PayloadAction<number>) => {
      state.size = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取规则列表
      .addCase(fetchRuleList.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchRuleList.fulfilled, (state, action) => {
        state.loading = false;
        state.ruleList = action.payload.data.list;
        state.total = action.payload.data.total;
        state.page = action.payload.data.page;
        state.size = action.payload.data.size;
      })
      .addCase(fetchRuleList.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取规则列表失败';
      })
      // 获取规则详情
      .addCase(fetchRuleDetail.fulfilled, (state, action) => {
        state.currentRule = action.payload.data;
      })
      // 创建规则
      .addCase(createRule.fulfilled, (state, action) => {
        state.ruleList.unshift(action.payload.data);
        state.total += 1;
      })
      // 更新规则
      .addCase(updateRule.fulfilled, (state, action) => {
        const index = state.ruleList.findIndex(rule => rule.id === action.payload.data.id);
        if (index !== -1) {
          state.ruleList[index] = action.payload.data;
        }
        if (state.currentRule && state.currentRule.basicInfo.id === action.payload.data.id) {
          state.currentRule.basicInfo = action.payload.data;
        }
      })
      // 删除规则
      .addCase(deleteRule.fulfilled, (state, action) => {
        state.ruleList = state.ruleList.filter(rule => rule.id !== action.payload);
        state.total -= 1;
      })
      // 预览规则
      .addCase(previewRule.fulfilled, (state, action) => {
        state.rulePreview = action.payload.data;
      })
      // 切换规则状态
      .addCase(toggleRuleStatus.fulfilled, (state, action) => {
        const index = state.ruleList.findIndex(rule => rule.id === action.payload.data.id);
        if (index !== -1) {
          state.ruleList[index].status = action.payload.data.status;
        }
      });
  },
});

export const {
  setCurrentRule,
  updateCurrentRule,
  clearError,
  setPage,
  setSize,
} = ruleSlice.actions;

export default ruleSlice.reducer;